package client

import (
	"bytes"
	"encoding/json"
	"fmt"
	"myLive/contact"
	"net"
)

const (
	defaultPort = "11111"
	defaultIp   = "127.0.0.1"
)

var (
	conn net.Conn
	err  error
)

func enjoyLive() {
	for {
		buf := make([]byte, 1024)
		if _, err = conn.Read(buf); err != nil {
			continue
		}

		buf = bytes.Trim(buf, "\u0000")
		var msg contact.Message

		_ = json.Unmarshal(buf, &msg)

		//if ctlMsg.Type == "Data" {
		//	fmt.Println(ctlMsg.Content)
		//}

		fmt.Println(msg)
	}
}

// JoinLive 客户加入直播间
func JoinLive() {
	fmt.Println("Joining ", defaultIp+":"+defaultPort)
	conn, err = net.Dial("tcp", defaultIp+":"+defaultPort)
	//defer client.Close()
	if err != nil {
		fmt.Println("Request Failed, ", err)
	}

	//if _, err := client.Write([]byte("Hello Server, I am client.")); err != nil {
	//	return
	//}

	buf := make([]byte, 64)
	conn.Read(buf)
	buf = bytes.Trim(buf, "\u0000")

	var msg contact.Message
	_ = json.Unmarshal(buf, &msg)
	fmt.Println(msg)

	if msg.Type == "ConnReq" && msg.Content == "ok" {
		enjoyLive()
	}
}
